#include <string.h>
#include <jni.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <android/log.h>
#include "rkGpioControl_jni.h"

#define  LOG_TAG    "rk_gpio_control_jni"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)

#define  DEVICE_NAME  "/dev/dev_rk_gpio"

int open_fd = -1;
int READ_GPIO = -1;

jint
Java_com_siecom_nativelibs_rkGpioControlNative_init( JNIEnv*  env )
{
	LOGD("rkGpioControlNative_init() \n");
	open_fd = open(DEVICE_NAME ,O_RDWR);
	if(open_fd<0){
		LOGE("=============== open device %s error!!! \n" ,DEVICE_NAME);
		return 0;
	}else{
		LOGE("================ open device %s success!!! \n",DEVICE_NAME);
		return 1;
	}
}

jint
Java_com_siecom_nativelibs_rkGpioControlNative_ControlGpio( JNIEnv*  env, jobject  thiz, jint which,jint state )
{
	 int gpio_id = which;
	 int result = -1;
	 int ret = -1;
	 //LOGD("================fd ===  %d !!! \n",fd);
	 //LOGD("================which ===  %d !!! \n",which);
	 if(open_fd != -1){
		 ret = ioctl(open_fd,which,state);
	 }
	 return ret;
}

jint
Java_com_siecom_nativelibs_rkGpioControlNative_ReadGpio( JNIEnv*  env, jobject  thiz, jint which )
{
	 int gpio_id = which;
	 int result = -1;
	 int ret = -1;
	 if(open_fd != -1){
		 ret = ioctl(open_fd , which,READ_GPIO);
	 }
	 return ret;
}

void
Java_com_siecom_nativelibs_rkGpioControlNative_close(JNIEnv*  env, jobject  thiz)
{
	if(open_fd != -1){
		close(open_fd);
	}
}



